import { getCartInfo, createOrder, approveOrder } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Modal, ModalHeader, ModalBody, Form, List, Button, Label, Toast } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';
import { PayPalScriptProvider, PayPalButtons } from "@paypal/react-paypal-js";
import { PayPalClientId } from "../../../../components/constant/constants";
import Loading from "../../../../components/common/Loading";

const CartPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;

  const [isLoading, setIsLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [payModelIsOpen, setPayModelIsOpen] = useState(false);
  const [cartList, setCartList] = useState([]);
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [checkoutTotal, setCheckoutTotal] = useState("");
  const [orderIds, setOrderIds] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const debounceRef = useRef(null);
  const router = useRouter();
  const [payLoading, setPayLoading] = useState(true);

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");

    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
          setCartList(res.data);
          let to = Number(0);
          var qtys = [];
          res.data.map(item => {
            to += parseFloat(item.price * item.quantity);
            qtys.push({
              "product_id": item.product_id,
              "quantity": item.quantity,
              "product_stock": item.product_stock,
              "price": item.price
            })
          })
          setTotal(getTwoDecimal(`${to}`));
          setQtyList(qtys);
        });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var user = localStorage.getItem("XYCLogin")
    if (!user) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

    debounceRef.current = debounce((item, quantity) => {
      changeProductCount({
        product_id: item.product_id,
        quantity: quantity
      })
    }, 1000);

    return () => {
      if (debounceRef.current) {
        debounceRef.current.cancel();
      }
    };
  }, [])

  const handleQtyUpdate = (item, quantity) => {
    if (quantity > 0 && quantity) {
      debounceRef.current(item, quantity);
      var newQtys = [];
      qtyList.map(q => {
        if (q.product_id != item.product_id)
          newQtys.push(q);
      });
      newQtys.push({
        "product_id": item.product_id,
        "quantity": quantity,
        "product_stock": item.product_stock,
        "price": item.price
      });
      setQtyList(newQtys);

      var newTotal = 0;
      newQtys.map(nq => {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      })
      setTotal(getTwoDecimal(`${newTotal}`))
    }
  };

  const removeProduct = (item) => {
    setCartList(v => v.filter(p => p.product_id != item.product_id));
    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
    var newTotal = 0;
    qtyList.map(nq => {
      if (nq.product_id != item.product_id) {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      }
    })
    setQtyList(v => v.filter(p => p.product_id != item.product_id));
    console.log(newTotal)
    setTotal(getTwoDecimal(`${newTotal}`))
  }

  const onCreateOrder = async (data, actions) => {
    return actions.order.create({
      purchase_units: [{
        amount: {
          currency_code: 'USD',
          value: checkoutTotal
        }
      }]
    })
  }

  const onApproveOrder = async (data, actions) => {
    const orderData = await actions.order?.capture();

    if (orderData?.status == 'COMPLETED') {
      await approveOrder({
        "payment_order_id": orderData?.id,
        "order_ids": orderIds
      }).then(res => {
        if (res.error_code == "2000") {
          toast.success("Checkout Succeed!");
          setPayModelIsOpen(false);
          location.reload();
        }
      })
    }
  }

  // const onError = () => {
  //   toast.warning("Checkout Error.");
  // }

  const confirmOrder = () => {
    setIsLoading(true);
    var list = [];
    qtyList.map(item => {
      list.push({
        "product_id": item.product_id,
        "quantity": item.quantity
      });
    });
    var json = {
      "order_list": list
    }
    createOrder(json).then(res => {
      if (res.error_code != "2000") {
        setIsLoading(false);
        toast.error("Create Order Failed.")
      }
      else {
        setCheckoutTotal(res.total_price);
        setOrderIds(res.order_ids);
        setIsOpen(false);
        setPayModelIsOpen(true);
      }
    });
  }

  return (
    <div>
      <Modal isOpen={payModelIsOpen} centered size="lg" style={{ width: 400 }}>
        <ModalHeader >Payment Provider
        </ModalHeader>
        <ModalBody>
          <div className="checkout-form">
            {payLoading && <Loading />}
            <div style={{ display: payLoading ? "none" : "inline" }}>
              <PayPalScriptProvider options={{ clientId: PayPalClientId }}>
                <PayPalButtons
                  createOrder={onCreateOrder}
                  onApprove={onApproveOrder}
                  // onError={onError}
                  onInit={() => setPayLoading(false)}
                  style={{ layout: "horizontal" }}
                />
              </PayPalScriptProvider>
            </div>
            <Button style={{ width: "100%", marginTop: 20 }} onClick={() => { setPayModelIsOpen(false); setIsLoading(false); location.reload(); }}>Cancel</Button>
          </div>
        </ModalBody>
      </Modal>
      <Modal isOpen={isOpen} centered size="lg" style={{ width: 600 }}>
        <ModalHeader >Order Confirm
        </ModalHeader>
        <ModalBody>
          <div className="checkout-form">
            <Row style={{ marginTop: 20 }}>
              <Col sm="12">
                <h3>{`Confirm payment? The total amount is `}<span style={{ color: 'red' }}>{symbol} {total}</span></h3>
              </Col>
            </Row>

            <Row style={{ marginTop: 20 }}>
              <Col sm="6">
                <Button style={{ minWidth: '100%' }} onClick={() => { setIsOpen(false) }} disabled={isLoading}>Cancel</Button>
              </Col>
              <Col sm="6">
                <Button color="primary" style={{ minWidth: '100%' }} onClick={() => { confirmOrder() }} disabled={isLoading}>Confirm</Button>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      {cartList && cartList.length > 0 ? (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <table className="table cart-table table-responsive-xs">
                  <thead>
                    <tr className="table-head">
                      <th scope="col">image</th>
                      <th scope="col">product name</th>
                      <th scope="col">price</th>
                      <th scope="col">quantity</th>
                      <th scope="col">total</th>
                      <th scope="col">action</th>
                    </tr>
                  </thead>
                  {cartList.map((item, index) => {
                    return (
                      <tbody key={index}>
                        <tr>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a className="order-list-product">
                                <Media
                                  src={item.product_media1 ? `${fileServerUrl}/${item.product_media1}` : `${fileServerUrl}/products/default.jpg`}
                                  alt=""
                                />
                              </a>
                            </Link>
                          </td>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a>{item.product_name}</a>
                            </Link>
                          </td>
                          <td>
                            <h2>
                              {symbol}
                              {getTwoDecimal(item.price)}
                            </h2>
                          </td>
                          <td>
                            <div className="qty-box">
                              <div className="input-group">
                                <input
                                  type="number"
                                  name="quantity"
                                  onChange={(e) =>
                                    handleQtyUpdate(item, e.target.value)
                                  }
                                  className="form-control input-number"
                                  defaultValue={item.quantity}
                                  style={{
                                    borderColor: quantityError && "red",
                                  }}
                                  min="1"
                                />
                              </div>
                            </div>
                            {item.quantity >= item.stock ? "out of Stock" : ""}
                          </td>
                          <td>
                            <h2 className="td-color">
                              {symbol}
                              {getTwoDecimal(`${parseFloat(item.price) * (qtyList.length > 0 ? parseFloat(qtyList.find(q => q.product_id == item.product_id).quantity) : parseFloat(item.quantity))}`)}
                            </h2>
                          </td>
                          <td>
                            <i
                              className="fa fa-times"
                              onClick={() => removeProduct(item)}
                            ></i>
                          </td>
                        </tr>
                      </tbody>
                    );
                  })}
                </table>
                <table className="table cart-table table-responsive-md">
                  <tfoot>
                    <tr>
                      <td>total price :</td>
                      <td>
                        <h2>
                          {symbol} {total}{" "}
                        </h2>
                      </td>
                    </tr>
                  </tfoot>
                </table>
              </Col>
            </Row>
            <Row className="cart-buttons">
              <Col xs="6">
                <Link href={`/`}>
                  <a className="btn btn-solid">continue shopping</a>
                </Link>
              </Col>
              <Col xs="6">
                <a className="btn btn-solid" onClick={() => { setIsOpen(true) }}>check out</a>
              </Col>
            </Row>
          </Container>
        </section>
      ) : (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <div>
                  <div className="col-sm-12 empty-cart-cls text-center">
                    <Media
                      src={cart}
                      className="img-fluid mb-4 mx-auto"
                      alt=""
                    />
                    <h3>
                      <strong>Your Cart is Empty</strong>
                    </h3>
                    <h4>Explore more shortlist some items.</h4>
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>
      )}
    </div>
  );
};

export default CartPage;
